<?php
/**
 * 系统配置模型
 *
 * Author:李强
 * Company:上海煦鸣网络科技有限公司
 * Date:2018-01-03
 */

namespace App\Models;


class Config extends CommonModel
{
    //
    protected $table = 'config';
    protected $guarded = [];
    protected $primaryKey = 'varname';
    protected $keyType = 'string';
    public $timestamps = false;


    /**
     * 返回所有配置信息
     *
     * @return array
     */
    public static function getAllConfig()
    {
        $configs = [];
        self::chunk(100, function ($list) use (&$configs) {
            foreach ($list as $config) {
                if ($config->is_json == 1) {
                    $config->value = json_decode($config->value, true);
                }
                $var_name = $config->varname;
                $configs[$var_name] = $config->toArray();
            }
        });
        return $configs;
    }

    /**
     * 获取某个配置项的值
     *
     * @param $varname
     * @param $default 默认值
     * @return string
     */
    public static function getConfig($varname,$default=''){
        $configs = self::getAllConfig();
        if(isset($configs[$varname])){
            return $configs[$varname]['value'];
        }else{
            return $default;
        }
    }
    /**
     * 更新配置项目
     *
     * @param $varname
     * @param $value
     * @return bool
     */
    public static function updateConfig($varname,$value){
        $setting = self::where('varname',$varname)->first();
        if(!is_null($setting)){
            $setting->value = $setting->is_json==1?json_encode($value):$value;
            $setting->save();
        }else{
            return false;
        }
        return true;
    }
}
